package cn.wolfcode.wolf2w.controller;


import cn.wolfcode.wolf2w.JsonResult.JsonResult;
import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelCommentService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.util.UMEditorUploader;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/travels")
public class TravelController {
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private ITravelService travelService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Autowired
    private ITravelCommentService travelCommentService;

    @GetMapping("/query")
    public Object query(TravelQuery qo){
        Page<Travel> page = travelService.query(qo);
        return  JsonResult.success(page);
    }

    @GetMapping("/input")
    public Object input(String id){
        List<Destination> dests=destinationService.list();
        Map<String , Object> map=new HashMap<>();
        if (StringUtils.hasLength(id)){
            Travel tv=travelService.get(id);
            map.put("tv",tv);
        }
        map.put("dests",dests);
        return JsonResult.success(map);
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }
    @RequireLogin
    @PostMapping("/saveOrUpdate")
    public Object saveOrUpdate(Travel travel,HttpServletRequest request){
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        travelService.saveOrUpdate(travel,user);

        //页面需要返回时新增/编辑游记
        return JsonResult.success(travel);
    }

    @GetMapping("/detail")
    public Object detail(String id){
        return JsonResult.success(travelService.get(id));
    }

    /*
    * 在接口中获取当前登录用户信息需要使用下面代码
    * @GetMapping("xxx")
    * public Object xxx(HttpServletRequest request){
    *       String token = request.getHeader("token");
    *       UserInfo user= userInfoRedisService.getUserByToken(token);
    * }
    * 如果多个接口都需要获取，这种操作方式就冗余了（多次重复操作）
    * 使用其他方式简化获取当前登录用户对象；
    * 简化方案原理：springmvc的参数解析器
    *
    * 接口（请求映射方法）中所有参数注入靠的springmvc默认参数解析实现的
    * 现在想要注入当前登录用户对象，不能使用springmvc的默认参数解析器
    * 需要自己额外定义一个用户参数解析器，专门来解析当前登录信息
    * 突破口：怎么自定义一个springmvc的参数解析器
    *
    * 最终简化效果
    * 在接口的形式参数中声明用户对象，springmvc自动将当前登录用户对象注入进来
    *
    * */

    @GetMapping("getUser")
    public Object getUser(@UserParam UserInfo userInfo){
        //获取当前登录用户对象
        return JsonResult.success(userInfo);
    }
    @GetMapping("updateUser")
    public Object updateUser(UserInfo userInfo){
        //获取当前登录用户对象
        return JsonResult.success(userInfo);
    }

    @PostMapping("/addComment")
    public Object commentAdd(TravelComment comment,@UserParam UserInfo userInfo){
        BeanUtils.copyProperties(userInfo,comment);
        comment.setUserId(userInfo.getId());
        travelCommentService.save(comment);
        return JsonResult.success();
    }

    @GetMapping("/comments")
    public  Object comments(String travelId){
        return JsonResult.success(travelCommentService.queryByTravelId(travelId));
    }
}
